package com.deepexi.sample.config;

import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import java.util.Arrays;

/**
 * 不建议使用Spring-data-elasticsearch方式集成ES
 */
@Configuration
public class ElasticsearchConfig {

    @Value("${elasticsearch.hosts}")
    private String hosts;
    @Value("${elasticsearch.port:9200}")
    private int port;
    @Value("${elasticsearch.scheme:http}")
    private String scheme;
    @Value("${elasticsearch.username}")
    private String userName;
    @Value("${elasticsearch.pwd}")
    private String pwd;

    //连接超时时间
    private final static int CONNECT_TIMEOUT = 5000;
    //连接超时时间
    private final static int SOCKET_TIMEOUT = 40000;
    //获取连接的超时时间
    private final static int CONNECTION_REQUEST_TIMEOUT = 1000;
    //最大连接数
    private final static int MAX_CONNECT_NUM = 100;
    //最大路由连接数
    private final static int MAX_CONNECT_ROUTE = 100;

    @Bean
    public RestHighLevelClient client() {
        HttpHost[] httpHosts = Arrays.stream(hosts.trim().split(",")).map(host -> new HttpHost(host.trim(), port, scheme.trim())).toArray(HttpHost[]::new);
        RestClientBuilder builder = RestClient.builder(httpHosts);
        builder.setRequestConfigCallback(requestConfigBuilder -> {
            requestConfigBuilder.setConnectTimeout(CONNECT_TIMEOUT);
            requestConfigBuilder.setSocketTimeout(SOCKET_TIMEOUT);
            requestConfigBuilder.setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT);
            return requestConfigBuilder;
        });

        builder.setHttpClientConfigCallback(httpClientBuilder -> {
            httpClientBuilder.setMaxConnTotal(MAX_CONNECT_NUM);
            httpClientBuilder.setMaxConnPerRoute(MAX_CONNECT_ROUTE);

            if (!StringUtils.isEmpty(userName) && !StringUtils.isEmpty(pwd)) {
                CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
                credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, pwd));
                httpClientBuilder.disableAuthCaching();
                return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
            }
            return httpClientBuilder;
        });

        return new RestHighLevelClient(builder);
    }
}
